
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletResponse;

@ControllerAdvice
public class MyControllerAdvice {
    /**
     * 用于捕获某种异常包括子类
     * @param exception
     * @param method
     * @param response
     * @return
     */
    @ExceptionHandler(Exception.class)
    public  String  handler(Exception exception, HandlerMethod method, HttpServletResponse response){
        exception.printStackTrace();
        System.out.println("出异常了");
        //判断原来的方法是否有贴ResponseBody注解
        if(method.hasMethodAnnotation(ResponseBody.class)){
            try {
               //TODO json的头信息
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().println(JSON.toJSONString(new main.java.cn.wolfcode.qo.JsonResult(false ,"系统异常,请联系管理员")));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return  null;
        }
        //返回错误页面的视图
         return "common/error";
    }

    /**
     * 捕获自定义的逻辑异常
     * @param e
     * @return
     */
    public main.java.cn.wolfcode.qo.JsonResult handlerLogicException (LoginException e){
        return  new main.java.cn.wolfcode.qo.JsonResult(false ,e.getMessage());
    }

}
